package com.bdqn.t362.order.servlet;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.bdqn.t362.order.entity.TB2COrder;
import com.bdqn.t362.order.entity.TB2COrderLine;
import com.bdqn.t362.order.entity.TProduct;
import com.bdqn.t362.order.service.TB2COrderService;
import com.bdqn.t362.order.service.impl.TB2COrderServiceImpl;
import com.bdqn.t362.pay.AlipayApiConfig;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lqm
 * @ClassName ${NAME}
 * @description:  提交订单并调用支付servlet
 */
@WebServlet("/CreateOrderServlet")
public class CreateOrderServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        TB2COrderService tb2COrderService = new TB2COrderServiceImpl();
        TB2COrder tb2COrder = new TB2COrder();
        //订单明细
        List<TB2COrderLine> orderLines = new ArrayList<>();

        //获取商品列表 service层
        List<TProduct> tempList = tb2COrderService.getProductList();
        for (int i = 0 ; i < tempList.size(); i++){
            TProduct tempEntity=tempList.get(i);
            //获取购物车提交的购买信息
            String productId=request.getParameter("productId_"+tempEntity.getId());
            String productNum=request.getParameter("productNum_"+tempEntity.getId());
            if(Integer.parseInt(productNum)>0){
                TB2COrderLine orderLine=new TB2COrderLine();
                orderLine.setId(Integer.parseInt(productId));
                orderLines.add(orderLine);
            }


        }
        //随机字符串
        String codeStr = "SO" +System.currentTimeMillis()+ (int) ((Math.random() * 9 + 1) * 1000);
        tb2COrder.setOrderCode(codeStr);

        //1.保存订单
        int count = tb2COrderService.addOrder(tb2COrder);


        if (count > 0) {
            TB2COrder tempEntity = tb2COrderService.getOrderByOrderCode(codeStr);
            //2.订单支付
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayApiConfig.URL,
                    AlipayApiConfig.APP_ID, AlipayApiConfig.PRIVATE_KEY, AlipayApiConfig.FORMAT,
                    AlipayApiConfig.CHARSET, AlipayApiConfig.ALIPAY_PUBLIC_KEY,
                    AlipayApiConfig.SIGN_TYPE);
            AlipayTradePagePayRequest req = new AlipayTradePagePayRequest();
//异步接收地址，仅支持http/https，公网可访问
//req.setNotifyUrl("");
//同步跳转地址，仅支持http/https
            req.setReturnUrl("http://localhost:8080/projectManager_war_exploded/PayCallBackServlet");
/******必传参数******/
            JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
            bizContent.put("out_trade_no", tempEntity.getOrderCode());
//支付金额，最小值0.01元
            bizContent.put("total_amount", tempEntity.getSumAmout());
//订单标题，不可使用特殊符号
            bizContent.put("subject", "XXXX系统订单");
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            req.setBizContent(bizContent.toString());
            AlipayTradePagePayResponse resp = null;
            try {
                resp = alipayClient.pageExecute(req);
            } catch (AlipayApiException e) {
                throw new RuntimeException(e);
            }
            if (resp.isSuccess()) {
                response.setCharacterEncoding("utf-8");
                PrintWriter out = response.getWriter();
                response.setContentType("text/html;charset=" + AlipayApiConfig.CHARSET);
                System.out.println(resp.getBody());
                out.print(resp.getBody());
                out.flush();
                out.close();
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }


        } else {

        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
